package com.totem.customer.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.totem.customer.vo.InvitePathVO;
import com.totem.customer.model.TInvite;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface TInviteMapper extends BaseMapper<TInvite> {

    @Select("WITH RECURSIVE invite_path AS (" +
            " SELECT i.invitee_id, i.inviter_id, m.member_level, 1 path_level" +
            " FROM t_invite i" +
            " INNER JOIN t_members m on i.invitee_id = m.customer_id" +
            " WHERE i.invitee_id = #{customerId}" +
            " UNION ALL" +
            " SELECT i.invitee_id, i.inviter_id, m.member_level, ip.path_level+1" +
            " FROM t_invite i" +
            " INNER JOIN invite_path ip on i.invitee_id = ip.inviter_id" +
            " INNER JOIN t_members m on i.invitee_id=m.customer_id" +
            //" WHERE i.member_level<=6" +
            ")" +
            " SELECT invitee_id, inviter_id, member_level, path_level" +
            " FROM invite_path" +
            " WHERE invitee_id is not null" +
            " ORDER BY path_level asc")
    List<InvitePathVO> findInvitePathByIdUntil(@Param("customerId") Long customerId);

    @Select("WITH RECURSIVE invite_path AS (" +
            " SELECT i.invitee_id, i.inviter_id, 1 path_level" +
            " FROM t_invite i" +
            " WHERE invitee_id = #{customerId}" +
            " UNION ALL" +
            " SELECT i.invitee_id, i.inviter_id, c.path_level+1" +
            " FROM t_invite i" +
            " INNER JOIN invite_path c ON c.inviter_id = i.invitee_id" +
            ")" +
            " SELECT invitee_id, inviter_id, path_level" +
            " FROM invite_path" +
            " WHERE invitee_id is not null" +
            " ORDER BY path_level asc")
    List<InvitePathVO> findInvitePathById(@Param("customerId") Long customerId);
}
